import 'package:flutter/material.dart';
import '../common/ScreenAdaper.dart';
import '../config/Config.dart';
import '../model/ProductModel.dart';
import 'package:dio/dio.dart';
import '../widget/LoadingWidget.dart';
import '../services/SearchServices.dart';

// ignore: must_be_immutable
class ProductListPage extends StatefulWidget {
  Map arguments;
  ProductListPage({Key key, this.arguments}) : super(key: key);
  _ProductListPageState createState() => _ProductListPageState();
}

class _ProductListPageState extends State<ProductListPage> {
  List _productData = [];
  int _page = 1;
  int _pageSize = 20;
  bool hasMore = true; //判断有没有数据
  ScrollController _scrollController = new ScrollController();
  //
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  // 获取商品列表
  _getListDate() async{
    if(hasMore){
      var apiUrl = "${Config.domain}api/plist?cid=${widget.arguments['cid']}&pageSize=${_pageSize}&page=${_page}";
      if(widget.arguments['keywords'] != null){
        apiUrl = "${Config.domain}api/plist?search=${widget.arguments['keywords']}&pageSize=${_pageSize}&page=${_page}";
      }
      print(apiUrl);
      Response result=await Dio().get(apiUrl);
      var list=ProductModel.fromJson(result.data);
      setState(() {
        this._productData.addAll(list.result);
        this._page++;
      });
      //判断是否是最后一页
      if (list.result.length == 0) {
        setState(() {
          this.hasMore = false;
        });
      }
    }
  }

  //筛选导航
  Widget _subHeaderWidget() {
    return Positioned(
      top: 0,
      height: S.height(80),
      width: S.width(750),
      child: Container(
        width: S.width(750),
        height: S.height(80),
        // color: Colors.red,
        decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(
                    width: 1, color: Color.fromRGBO(233, 233, 233, 0.9)))),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: InkWell(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(
                      0, S.height(16), 0, S.height(16)),
                  child: Text(
                    "综合",
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.red),
                  ),
                ),
                onTap: () {},
              ),
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(
                      0, S.height(16), 0, S.height(16)),
                  child: Text("销量", textAlign: TextAlign.center),
                ),
                onTap: () {},
              ),
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(
                      0, S.height(16), 0, S.height(16)),
                  child: Text("价格", textAlign: TextAlign.center),
                ),
                onTap: () {},
              ),
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(
                      0, S.height(16), 0, S.height(16)),
                  child: Text("筛选", textAlign: TextAlign.center),
                ),
                onTap: () {
                  _scaffoldKey.currentState.openEndDrawer();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 2000), () {
      print('请求数据完成');
      _getListDate();
    });
  }

  // 商品列表组件
  Widget _listWidget(){
    return ListView.builder(
      controller: _scrollController,// 监听滚动条事件
      itemBuilder: (context, index) {
        var img = Config.domain + _productData[index].pic.replaceAll('\\', '/');

        if(index == _productData.length - 1){ // 列表渲染到最后一条,出现加载圈圈，数据展示完显示---底线
          if(hasMore == false){ // 没有数据的时候
            return Center(
              child: Text("--------我是有底线的--------"),
            );
          } else{
            if(_page == 2 && _productData.length < _pageSize){// 防止第一页就加载完数据而一直显示加载中
              return Column( // 当期分页完成时
                children: <Widget>[
                  _listWidget2(index, img),
                  Divider(height: S.height(40),),
                  Text("--------我是有底线的--------"),
                ],
              );
            } else {
              return Column( // 当期分页完成时
                children: <Widget>[
                  _listWidget2(index, img),
                  Divider(height: S.height(40),),
                  LoadingWidget(),
                ],
              );
            }
          }
        } else {
          return Column(
            children: <Widget>[
              _listWidget2(index, img),
              Divider(height: S.height(40),)
            ],
          );
        }
      },
      itemCount: this._productData.length,
    );
  }

  // 商品组件
  _listWidget2(index,img){
    return Row(
      children: <Widget>[
        Container(
          width: S.width(180),
          height: S.height(180),
          child: Image.network("${img}", fit: BoxFit.cover),),
        Expanded(
          flex: 1,
          child: Container(
            height:S.height(180) ,
            margin: EdgeInsets.only(left: 10),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text("${_productData[index].title}",maxLines: 2,overflow: TextOverflow.ellipsis,),
                Row(
                  children: <Widget>[
                    Container(
                      height: S.height(36),
                      margin: EdgeInsets.only(right: 10),
                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      //注意 如果Container里面加上decoration属性，这个时候color属性必须得放在BoxDecoration
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: Color.fromRGBO(230, 230, 230, 0.9),
                      ),
                      child: Text("4g"),
                    ),
                    Container(
                      height: S.height(36),
                      margin: EdgeInsets.only(right: 10),
                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: Color.fromRGBO(230, 230, 230, 0.9),
                      ),
                      child: Text("126"),
                    ),
                  ],
                ),
                Text("¥${_productData[index].price}",style:TextStyle(color: Colors.red, fontSize: 16),
                )
              ],
            ),
          ),
        ),
      ],
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getListDate();

    //监听滚动条事件
    _scrollController.addListener(() {
      print(_scrollController.position.pixels); //获取滚动条下拉的距离
      print(_scrollController.position.maxScrollExtent); //获取整个页面的高度
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 40) {
        this._getListDate();
      }
    });

    this._keywords=widget.arguments["keywords"];
    //给search框框赋值
    this._initKeywordsController.text=this._keywords;
  }

  //配置search搜索框的值
  var _initKeywordsController=new TextEditingController();
  var _keywords;

  @override
  Widget build(BuildContext context) {
    S.init(context);
    return Scaffold(
      appBar: AppBar(
        title: Container(
          child: TextField(
            controller: this._initKeywordsController,
            autofocus: false,
            decoration: InputDecoration(
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(30),
                    borderSide: BorderSide.none)),
            onChanged: (value){
              setState(() {
                this._keywords=value;
              });
            },
          ),
          height: S.height(68),
          decoration: BoxDecoration(
              color: Color.fromRGBO(233, 233, 233, 0.8),
              borderRadius: BorderRadius.circular(30)),
        ),
        actions: <Widget>[
          InkWell(
            child: Container(
              height: S.height(68),
              width: S.width(80),
              child: Row(
                children: <Widget>[Text("搜索")],
              ),
            ),
            onTap: () {
              SearchServices.setHistoryData(this._keywords);
              Navigator.pushReplacementNamed(context, '/productList',arguments: {
                "keywords":this._keywords
              });
            },
          )
        ],
      ),
      body: Stack(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: S.height(80)),
            padding: EdgeInsets.all(S.width(20)),
            child: RefreshIndicator(
              onRefresh: _onRefresh,
              child: _listWidget(),
            ),
          ),
          _subHeaderWidget(),
        ],
      ),
    );
  }
}